package xin.baizhiedu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import xin.baizhiedu.dao.UserDao;
import xin.baizhiedu.entity.User;

import java.nio.charset.StandardCharsets;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    // 用户登录
    @Override
    public User login(String username, String password) {
        // 1.根据用户名查询用户
        User user = userDao.findUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) throw new RuntimeException("用户名错误！");
        // 2.比较密码
        String newPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!newPassword.equals(user.getPassword())) throw new RuntimeException("密码错误!");
        return user;
    }

    // 注册用户
    @Override
    public void registerUser(User user) {
        // 1.根据用户名查询数据库中是否存在该用户
        User userDB = userDao.findUserByUsername(user.getUsername());
        // 2.判断用户是否存在
        if (!ObjectUtils.isEmpty(userDB)) throw new RuntimeException("当前用户名已被注册！");
        // 3.注册用户 & 明文的密码加密
        String newPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        user.setPassword(newPassword);  
        userDao.save(user);
    }

}
